package com.system.demo.service.MainPage.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.system.demo.commonService.RedisService;
import com.system.demo.entity.mailPage.*;
import com.system.demo.mapper.*;
import com.system.demo.service.MainPage.MailPageService;
import com.system.demo.tool.ResponseResult;
import com.system.demo.utils.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.system.demo.service.constant.HomePageConstant.CAROUSEL_FILE_PATH;

@Service
public class MailPageServiceImpl implements MailPageService {

    @Autowired
    private CognizanceMapper cognizanceMapper;
    @Autowired
    private SubmitApplicationMapper submitApplicationMapper;
    @Autowired
    private PaperSubmitMapper paperSubmitMapper;
    @Autowired
    private LeaveMapper leaveMapper;
    @Autowired
    private CarouselMapper carouselMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserNotificationsMapper userNotificationsMapper;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Autowired
    private MinioUtils minioUtils;

    @Value("${myIp.ip}")
    private String ip;

    @Value("${minio.port}")
    private int port;


    @Override
    public ResponseResult<?> getData() {
        // 首先获取当前用户id
        String uid = StpUtil.getLoginId().toString();

        // 创建返回VO
        HomePageVO homePageVO = new HomePageVO();

        // 根据uid查询竞赛表中有多少status=5的 获取出竞赛ids
        List<Integer> competitionIds = submitApplicationMapper.selectIdsByUidAndStatus(uid);

        CognizanceVO cognizanceVO;
        // 根据竞赛ids查找cognizance表中 final rank name为0 1 2有多少项目
        if (!competitionIds.isEmpty()) {
            cognizanceVO = cognizanceMapper.selectRankCounts(competitionIds);
            if (cognizanceVO == null) {
                cognizanceVO = new CognizanceVO();
                cognizanceVO.setCount(0);
                cognizanceVO.setNational(0);
                cognizanceVO.setProvincial(0);
                cognizanceVO.setSchool(0);
            }
        } else {
            //该用户没有状态为5的竞赛 全部设置为0
            cognizanceVO = new CognizanceVO();
            cognizanceVO.setCount(0);
            cognizanceVO.setNational(0);
            cognizanceVO.setProvincial(0);
            cognizanceVO.setSchool(0);
        }
        homePageVO.setCognizanceVO(cognizanceVO);

        // 查通过认定的论文\专利\软著
        PaperVO paperVO = paperSubmitMapper.selectTypeCounts(uid);
        if (paperVO == null) {
            paperVO = new PaperVO();
            paperVO.setCount(0);
            paperVO.setPaper(0);
            paperVO.setPatent(0);
            paperVO.setSoftware(0);
        }
        homePageVO.setPaperVO(paperVO);

        // 查请假的
        LeaveVO leaveVO = leaveMapper.selectStatusCountsByUser(uid);
        if (leaveVO == null) {
            leaveVO = new LeaveVO();
            leaveVO.setCount(0);
            leaveVO.setLeaving(0);
            leaveVO.setVerifiedReturn(0);
            leaveVO.setOvernightStay(0);
        }
        homePageVO.setLeaveVO(leaveVO);

        // 将结果赋给HomePageVO中的CognizanceVO
        return ResponseResult.success("查询成功", homePageVO);
    }

    @Override
    public ResponseResult<?> getDataByAdmin() {
        // 创建返回VO
        HomePageVO homePageVO = new HomePageVO();

        // 统计出竞赛中全部的奖项
        CognizanceVO cognizanceVO = cognizanceMapper.selectRankCountsByAdmin();
        if (cognizanceVO == null) {
            cognizanceVO = new CognizanceVO();
            cognizanceVO.setCount(0);
            cognizanceVO.setNational(0);
            cognizanceVO.setProvincial(0);
            cognizanceVO.setSchool(0);
        }
        homePageVO.setCognizanceVO(cognizanceVO);

        // 统计出论文表中所有的论文专利软著多少项
        PaperVO paperVO = paperSubmitMapper.selectTypeCountsByAdmin();
        if (paperVO == null) {
            paperVO = new PaperVO();
            paperVO.setCount(0);
            paperVO.setPaper(0);
            paperVO.setPatent(0);
            paperVO.setSoftware(0);
        }
        homePageVO.setPaperVO(paperVO);

        // 统计出请假表中所有的数据
        LeaveVO leaveVO = leaveMapper.selectStatusCountsByAdmin();
        if (leaveVO == null) {
            leaveVO = new LeaveVO();
            leaveVO.setCount(0);
            leaveVO.setLeaving(0);
            leaveVO.setVerifiedReturn(0);
            leaveVO.setOvernightStay(0);
        }
        homePageVO.setLeaveVO(leaveVO);

        return ResponseResult.success("查询成功", homePageVO);
    }

    @Override
    public ResponseResult<?> getWork() {
        //查询竞赛待审批 待认定多少项
        CompetitionWorkVO competitionWorkVO = submitApplicationMapper.selectStatusCounts();

        //查询论文待审批 待认定多少项
        PaperWorkVO paperWorkVO = paperSubmitMapper.selectStatusCounts();

        //查询请假未审批 待销假多少项
        LeaveWorkVO leaveWorkVO = leaveMapper.selectStatusCounts();
        HomePageAdminWorkVO homePageAdminWorkVO = new HomePageAdminWorkVO();
        homePageAdminWorkVO.setCompetitionWorkVO(competitionWorkVO);
        homePageAdminWorkVO.setPaperWorkVO(paperWorkVO);
        homePageAdminWorkVO.setLeaveWorkVO(leaveWorkVO);
        return ResponseResult.success("查询成功", homePageAdminWorkVO);
    }

    @Override
    public ResponseResult<?> addCarousel(CarouselDTO carouselDTO) {

        //上传到minio中
        /*
         * 上传文件到MinIO服务器
         *
         * @param file 要上传的文件
         * @param bucketName 桶名
         * @param path 文件保存的路径（不包含文件名） carousel/文件名
         * @param objectName 对象名称（即文件名）
         * @return 如果上传成功返回true，否则返回false
         */
        try{
            String originalFilename = carouselDTO.getImg().getOriginalFilename();
            boolean uploadSuccess = minioUtils.uploadFile(carouselDTO.getImg(), bucketName, CAROUSEL_FILE_PATH, originalFilename);
            if (!uploadSuccess) {
                return ResponseResult.InternalServerError("文件上传失败");
            }

            String imgUrl = "http://" + ip + ":" + port + "/" + bucketName + "/" + CAROUSEL_FILE_PATH + "/" + originalFilename;
            Carousel carousel = new Carousel();
            carousel.setTopic(carouselDTO.getTopic());
            carousel.setImgUrl(imgUrl);
            carousel.setToUrl(carouselDTO.getToUrl());

            //上传到数据库中
            if(!(carouselMapper.insert(carousel) > 0)){
                return ResponseResult.InternalServerError("服务器内部错误，上传失败，请重试");
            }

            //获取到所有的轮播数据 放在redis中 时间设置为永久，下次添加或者删除再改就行
            List<Carousel> carousels = carouselMapper.selectList(null);
            String token = "carousel";
            redisService.setTokenKey(token, carousels, -1, TimeUnit.DAYS);

            return ResponseResult.success("添加轮播图成功", carousels);
        }catch (Exception e){
            return ResponseResult.InternalServerError("服务器内部错误" + e.getMessage());
        }


    }

    @Override
    public ResponseResult<?> getCarousels() {
        //用户登录获取主页轮播图
        String token = "carousel";
        List<Carousel> carouselList = redisService.getTokenKeyAsList(token, Carousel.class);
        //这个请求比较频繁 所以放在redis中
        return ResponseResult.success("获取轮播图成功", carouselList);
    }

    @Override
    public ResponseResult<?> deleteCarousel(Integer carouselId) {
        //管理员删除轮播图
        if(!(carouselMapper.deleteById(carouselId) > 0)){
            return ResponseResult.InternalServerError("删除轮播图失败，请稍后重试");
        }
        //更新redis缓存
        List<Carousel> carousels = carouselMapper.selectList(null);
        String token = "carousel";
        redisService.setTokenKey(token, carousels, -1, TimeUnit.DAYS);
        return ResponseResult.success("删除轮播图成功");
    }

}
